﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_DeviceMaintanceController : MvcControllerBase
    {
        /// <summary>
        /// 保养项目类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult TypeIndex()
        {
            return View();
        }
        
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult TypeForm()
        {
            return View();
        }

        /// <summary>
        /// 保养项目
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentForm()
        {
            return View();
        }

        #region 获取数据
        /// <summary>
      /// 获取项目类型树
      /// </summary>
      /// <returns></returns>
        public ActionResult GetWorkTypeTreeJson()
        {
            var data = new WorkBLL().GetWorkTypeList().ToList();
            List<TreeEntity> lst = new List<TreeEntity>();
            foreach (WorkTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.Id == item.ParentId) != 0 || item.ParentId == "0" ? true : false;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                tree.Attribute = "ExecRoleId";
                tree.AttributeValue = item.ExecRoleId;
                tree.AttributeA = "ResposeDept";
                tree.AttributeValueA = item.ResponseDept;
                lst.Add(tree);

            }
            return Content(lst.TreeToJson());

        }


        /// <summary>
        /// 获取工作类型集合
        /// </summary>
        /// <param name="queryjson">筛选条件</param>
        /// <returns></returns>
        public ActionResult GetWorkTypeList(string queryjson)
        {
            var data = new WorkBLL().GetWorkTypeList().ToList();
            var queryParam = queryjson.ToJObject();
            if (!queryParam["Type"].IsEmpty())
            {
                if (data.Count(e => e.ParentId == queryParam["Type"].ToString()) != 0)
                {
                    data = data.Where(e => e.ParentId == queryParam["Type"].ToString()).ToList();
                }
                else
                {
                    data = data.Where(e => e.Id == queryParam["Type"].ToString()).ToList();
                }
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }
            }
            var TreeList = new List<TreeGridEntity>();
            foreach (WorkTypeEntity item in data)
            {
                TreeGridEntity tree = new TreeGridEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.parentId = data.Count(t => t.Id == item.ParentId) == 0 ? "0" : item.ParentId;
                tree.expanded = true;
                tree.hasChildren = hasChildren;
                tree.entityJson = item.ToJson();
                TreeList.Add(tree);
            }
            return Content(TreeList.TreeJson());

        }

        /// <summary>
        /// 获取工作类型实体
        /// </summary>
        /// <param name="keyValue">实体主键</param>
        /// <returns></returns>
        public ActionResult GetWorkTypeEntity(string keyValue)
        {
            var data = new WorkBLL().GetWorkTypeEntity(keyValue);
            return Content(data.ToJson());
        }


        /// <summary>
        /// 获取工作项目集合
        /// </summary>
        /// <param name="queryjson">筛选条件</param>
        /// <returns></returns>
        public ActionResult GetWorkItemList(string queryjson)
        {
            var data = new WorkBLL().GetWorkItemList().ToList();
            var queryParam = queryjson.ToJObject();
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                data = data.Where(e => e.OrganizeId == queryParam["OrganizeId"].ToString()).ToList();
            }
            if (!queryParam["Type"].IsEmpty())
            {
                data = data.Where(e => e.Type == queryParam["Type"].ToString()).ToList();
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }
            }
            foreach (WorkItemEntity item in data)
            {
                item.Type = !new WorkBLL().GetWorkTypeEntity(item.Type).IsEmpty() ? new WorkBLL().GetWorkTypeEntity(item.Type).Name : "--";
            }

            var query = from s in data
                        select new
                        {
                            s.Id,
                            s.Code,
                            s.Name,
                            s.Content,
                            s.Memo,
                            s.Type,
                            InstallType = GetName(1, s.Id),
                            Level = GetName(2, s.Id),
                            BllTypeId = GetName(3, s.Id)
                        };
            return Content(query.ToJson());
        }

        /// <summary>
        /// 获取工作项目实体
        /// </summary>
        /// <param name="keyValue">实体主键</param>
        /// <returns></returns>
        public ActionResult GetWorkItemEntity(string keyValue)
        {

            var entity = new WorkBLL().GetWorkItemEntity(keyValue);
            var TypeName = new WorkBLL().GetWorkTypeEntity(entity.Type).Name;
            var query = new DeviceBLL().GetRelationDeviceItemList(2, null);
            query = query.Where(e => e.ItemId == keyValue).ToList();
            string DeviceLevel = "";
            string ProjectType = "";
            string DeviceTypeId = "";
            if (query.Count() != 0)
            {
                foreach (RelationDeviceItemEntity item in query)
                {
                    if (!DeviceLevel.Contains(item.DeviceLevel))
                    {
                        DeviceLevel += item.DeviceLevel + ",";
                    }
                    if (!ProjectType.Contains(item.ProjectType))
                    {
                        ProjectType += item.ProjectType + ",";
                    }
                    if (!DeviceTypeId.Contains(item.DeviceTypeId))
                    {
                        DeviceTypeId += item.DeviceTypeId + ",";
                    }
                }
                DeviceLevel = DeviceLevel.Contains(",") ? DeviceLevel.Substring(0, DeviceLevel.Length - 1) : "";
                ProjectType = ProjectType.Contains(",") ? ProjectType.Substring(0, ProjectType.Length - 1) : "";
                DeviceTypeId = DeviceTypeId.Contains(",") ? DeviceTypeId.Substring(0, DeviceTypeId.Length - 1) : "";
            }
            entity.ContentDetail = "[" + entity.ContentDetail + "]";
            var data = new
            {
                data1 = entity,
                data2 = DeviceLevel,
                data3 = ProjectType,
                data4 = DeviceTypeId,
                data5 = TypeName
            };
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取设备类型复选框树
        /// </summary>
        /// <param name="DeviceTypeId"></param>
        /// <returns></returns>
        public ActionResult GetCheckBoxTreeJson(string DeviceTypeId)
        {
            var data = new DeviceTypeBLL().GetList().ToList();
            var treeList = new List<TreeEntity>();
            treeList.Add(new TreeEntity() { id = "All", value = "All", text = "所有设备", parentId = "0", showcheck = true, checkstate = 0, hasChildren = true, isexpand = true, complete = true });
            foreach (DeviceTypeEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentId == "0" ? "All" : item.ParentId;
                tree.showcheck = true;
                tree.isexpand = true;
                tree.checkstate = DeviceTypeId.Contains(item.Id) ? 1 : 0;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.title = hasChildren == false ? "0" : "1";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 获取设备等级复选框集合
        /// </summary>
        /// <param name="keyValue">设备等级主键集合</param>
        /// <returns></returns>
        public ActionResult GetDeviceLeveCheckBox(string keyValue)
        {
            string html = "";           
            var data = new DataItemCache().GetDataItemList("DeviceLevel");
            foreach (var item in data)
            {
                html += "<label><input id=\"" + item.ItemDetailId + "\" name='checkLevel' onchange='GetDiviceList();' value=\"" + item.ItemDetailId + "\"type='checkbox'";
                html += keyValue.Contains(item.ItemDetailId) ? "checked" : "";
                html += "/> " + item.ItemName + " </label>";
            }
            return Content(html);
        }

        /// <summary>
        /// 获取项目类型复选框集合
        /// </summary>
        /// <param name="keyValue">楼盘主键集合</param>
        /// <returns></returns>
        public ActionResult GetProjectTypeCheckBox(string keyValue)
        {
            string html1 = "";
            var data = new DataItemCache().GetDataItemList("ProjectType");           
            foreach (var item in data)
            {
                html1 += "<label><input id=\"" + item.ItemDetailId + "\" name='checkType' onchange='GetDiviceList();' value=\"" + item.ItemDetailId + "\"type='checkbox'";
                html1 += keyValue.Contains(item.ItemDetailId) ? "checked" : "";
                html1 += "/> " + item.ItemName + " </label>";
            }
            return Content(html1);
        }
        public ActionResult GetDeviceList(string queryjson)
        {
            var data = new DeviceBLL().GetList().ToList();
            var queryParam = queryjson.ToJObject();
            string DeviceLevel = queryParam["Level"].ToString();
            string ProjectType = queryParam["Project"].ToString();
            string DeviceTypeId = queryParam["Type"].ToString();
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                var OrganizeId = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                data = data.Where(t => OrganizeId.Contains(t.OrganizeId)).ToList();
            }
            data = data.Where(e => DeviceLevel.Contains(e.Level) && DeviceTypeId.Contains(e.Type)).ToList();
            List<object> objlist = new List<object>();
            foreach (var item in data)
            {
                var TypeName = new DeviceTypeBLL().GetEntity(item.Type).IsEmpty() ? "" : new DeviceTypeBLL().GetEntity(item.Type).Name;
                var dd = new DataItemCache().GetDataItemList("DeviceLevel").FirstOrDefault(e => e.ItemDetailId == item.Level);
                var Level = dd.IsEmpty() ? "" : dd.ItemName;
                var organize = new OrganizeCache().GetEntity(item.OrganizeId);
                if (organize.IsEmpty() || !ProjectType.Contains(organize.BusinessScope))
                {
                    continue;
                }
                objlist.Add(new { Id = item.Id, TypeId = item.Type, Type = TypeName, LevelValue = item.Level, Level = Level, Code = item.Code, Name = item.Name, OrganizeId = item.OrganizeId, ProjectType = organize.BusinessScope });
            }
            return Content(objlist.ToJson());
        }

#endregion


        #region 提交数据
        /// <summary>
        /// 保存工作项目
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="entity">项目实体</param>
        /// <param name="DeviceLevel">应用设备等级集合</param>
        /// <param name="ProjectType">应用楼盘集合</param>
        /// <param name="DeviceTypeId">应用设备类型集合</param>
        /// <returns></returns>
        public ActionResult SaveWorkItemForm(string keyValue, WorkItemEntity entity, string DeviceLevel, string ProjectType, string DeviceTypeId)
        {

            entity.Category = 1;
            entity.EnabledMark = 1;
            entity.ContentDetail = entity.ContentDetail.Remove(0, 1);
            entity.ContentDetail = entity.ContentDetail.Remove(entity.ContentDetail.Length - 1);
            List<RelationDeviceItemEntity> lst = new List<RelationDeviceItemEntity>();
            string[] level = DeviceLevel.Split(',');
            string[] projecttype = ProjectType.Split(',');
            string[] devicetypeid = DeviceTypeId.Split(',');
            for (int i = 0; i < level.Length; i++)
            {
                for (int j = 0; j < projecttype.Length; j++)
                {
                    for (int k = 0; k < devicetypeid.Length; k++)
                    {
                        lst.Add(new RelationDeviceItemEntity()
                        {
                            ItemTag = 2,
                            ItemType = entity.Type,
                            OrganizeId = entity.OrganizeId,
                            DeviceLevel = level[i],
                            ProjectType = projecttype[j],
                            DeviceTypeId = devicetypeid[k],

                        });
                    }
                }
            }
            try
            {
                new WorkBLL().SaveWorkItemForm(keyValue, entity, lst);
                return Success("操作成功！");
            }
            catch (Exception e)
            {

                return Error(e.Message);
            }
        }

        /// <summary>
        /// 删除工作项目
        /// </summary>
        /// <param name="keyValue">项目主键</param>
        /// <returns></returns>
        public ActionResult RemoveWorkItemForm(string keyValue)
        {
            new WorkBLL().RemoveWorkItemForm(keyValue);
            return Success("操作成功");
        }
        


        /// <summary>
        /// 保存工作类型
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public ActionResult SaveWorkTypeForm(string keyValue, WorkTypeEntity entity)
        {
            entity.EnabledMark = 1;
            try
            {
                new WorkBLL().SaveWorkTypeForm(keyValue, entity);
                return Success("操作成功！");
            }
            catch (Exception e)
            {

                return Error(e.Message);
            }

        }

        /// <summary>
        /// 删除工作类型
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public ActionResult RemoveWorkTypeForm(string keyValue)
        {
            var query = new WorkBLL().GetWorkItemList().ToList();
            query = query.Where(e => e.Type == keyValue).ToList();
            var data = new WorkBLL().GetWorkTypeList().ToList();
            data = data.Where(e => e.ParentId == keyValue).ToList();
            if (data.Count() != 0)
            {
                return Error("该类型下挂有子类，请先删除子类！");
            }
            if (query.Count() != 0)
            {
                return Error("该类型下挂有项目无法删除！");
            }
            try
            {
                new WorkBLL().RemoveWorkTypeForm(keyValue);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        #endregion

        /// <summary>
        /// 获取应用集合
        /// </summary>
        /// <param name="type">应用类型</param>
        /// <param name="ItemId"></param>
        /// <returns></returns>
        private string GetName(int type, string ItemId)
        {
            string str = "";
            var query = new DeviceBLL().GetRelationDeviceItemList(2, null).ToList();
            query = query.Where(e => e.ItemId == ItemId).ToList();
            if (query.Count() <= 0)
            {
                return str;
            }
            switch (type)
            {
                case 1: //应用设备类型
                    foreach (var item in query)
                    {
                        var s = new DeviceTypeBLL().GetEntity(item.DeviceTypeId);
                        string Name = s.IsEmpty() ? "" : s.Name;
                        if (!str.Contains(Name))
                        {
                            str += Name + "|";
                        }
                    }
                    break;

                case 2://应用设备等级
                    foreach (var item in query)
                    {
                        var s = new DataItemDetailBLL().GetEntity(item.DeviceLevel);
                        string Name = s.IsEmpty() ? "" : s.ItemName;
                        if (!str.Contains(Name))
                        {
                            str += Name + "|";
                        }
                    }
                    break;

                case 3://应用项目类型
                    foreach (var item in query)
                    {
                        var s = new DataItemDetailBLL().GetEntity(item.ProjectType);
                        string Name = s.IsEmpty() ? "" : s.ItemName;
                        if (!str.Contains(Name))
                        {
                            str += Name + "|";
                        }

                    }
                    break;
                default:
                    break;
            }
            if (!str.IsEmpty())
            {
                str = str.Substring(0, str.LastIndexOf('|'));
            }
            return str;
        }
    }
}
